package com.xiequn;

import com.utils.Encryptions;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * Created by full on 2018/4/27.
 */
public class RegisterMacToDB {

    public static void toMySQL(String desPath,DBean db,boolean isUpdate) throws Exception {

        Class.forName("com.mysql.jdbc.Driver");// 加载mysql驱动程序
        Connection con = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPassword());// 获取连接
        PreparedStatement pre = null;// 创建预编译语句对象，一般都是用这个而不用Statement
        System.out.println("数据库连接成功: "+db.getUrl());

        try {
            File root = new File(desPath);
            File[] fs = root.listFiles();
            int result = 0;// 创建一个结果集对象
            for (int i = 0; i < fs.length; i++) {

                File zipFile = fs[i];
                if (".svn".equals(zipFile.getName())) {
                    continue;
                }
                BufferedInputStream br = new BufferedInputStream(new FileInputStream(zipFile));
                String bsnCode = zipFile.getName();

                String chkSum = Encryptions.mdEncode(Encryptions.getFileByte(br), Encryptions.SHA_1, false);
                System.out.println("BSN = " + bsnCode + "  CHK = " + chkSum);

                String sql = "update X_MENU set XMU_CHKSUM = ? where XMU_PKG = ?"; // 预编译语句，“？”代表参数
                pre = con.prepareStatement(sql);// 实例化预编译语句
                pre.setString(1, chkSum);// 设置参数，前面的1表示参数的索引，而不是表中列名的索引
                pre.setString(2, bsnCode);// 设置参数，前面的1表示参数的索引，而不是表中列名的索引
                System.out.println("PRE_SQL = " + pre);
                if (isUpdate) {
                    result = pre.executeUpdate();//.executeQuery();// 执行查询，注意括号中不需要再加参数
                    System.out.println("  Result: " + result);
                }

            }
        } finally {
            try {
                // 逐一将上面的几个对象关闭，因为不关闭的话会影响性能、并且占用资源
                // 注意关闭的顺序，最后使用的最先关闭
                if (pre != null)
                    pre.close();
                if (con != null)
                    con.close();
                System.out.println("数据库连接已关闭！");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
